package panda.client.listeners;

import panda.client.Cardpanda;
import panda.client.ui.widgets.BinExplorer;

import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;

/**
 * A MouseListener for the top label of a BinExplorer. Dragging the label enables the entire BinExplorer object to move.
 * 
 * @author zane.tian@gmail.com
 */
public class BinExplorerMouseHandler implements MouseOverHandler, MouseMoveHandler, MouseDownHandler, MouseUpHandler,
		MouseOutHandler {
	private boolean dragging = false;
	private int xOffset; // position in source widget where mouse is before dragging
	private int yOffset;

	private BinExplorer ex;

	public BinExplorerMouseHandler(BinExplorer ex) {
		this.ex = ex;
	}
	
	public void onMouseOver(MouseOverEvent event) {
		ex.addStyleName("mouseStyle-mouseover");
	}

	public void onMouseDown(MouseDownEvent event) {
		int x = event.getX();
		int y = event.getY();
		Widget source = (Widget) event.getSource();
		
		ex.addStyleName("mouseStyle-dragging");

		DOM.setCapture(source.getElement());
		dragging = true;
		xOffset = x;
		yOffset = y;
	}
	
	public void onMouseMove(MouseMoveEvent event) {
		if(dragging) {
			int x = event.getX();
			int y = event.getY();
			Widget source = (Widget) event.getSource();
			
			int xAbs = x + source.getAbsoluteLeft() - Cardpanda.canvas.getAbsoluteLeft();
			int yAbs = y + source.getAbsoluteTop() - Cardpanda.canvas.getAbsoluteTop();
			Cardpanda.canvas.setWidgetPosition(ex, xAbs - xOffset, yAbs - yOffset);
		}
	}

	public void onMouseUp(MouseUpEvent event) {
		Widget source = (Widget) event.getSource();
		ex.removeStyleName("mouseStyle-dragging");
		DOM.releaseCapture(source.getElement());
		dragging = false;
	}

	public void onMouseOut(MouseOutEvent event) {
		ex.removeStyleName("mouseStyle-mouseover");
	}
}